package com.lagou.spring_session.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RequestInterceptor implements HandlerInterceptor {

    /**
     * 登录拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取session
        HttpSession session = request.getSession();
        System.out.println("获取到的sessionId: " + session.getId());
        //2. 获取session中用户数据
        Object username = session.getAttribute("username");
        if (username == null) {
            //3. 登录失败，重定向到登陆页面
            System.out.println("当前用户尚未登录");
            response.sendRedirect(request.getContextPath() + "/login/toLogin");
            return false;
        }
        //4. 登录成功，放行
        System.out.println("当前登录用户为：" + username);
        return true;
    }
}
